package com.ruigi.control;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruigi.pojo.Employee;
import com.ruigi.pojo.R;
import com.ruigi.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("employee")
public class EmployeeControl {
    @Autowired
    private EmployeeService employeeService;

    //User login
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpServletRequest request) {
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        LambdaQueryWrapper<Employee> Wrapper = new LambdaQueryWrapper<>();
        Wrapper.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(Wrapper);
        if (emp == null) {
            return R.error("登录失败");

        }
        if (!emp.getPassword().equals(password)) {
            return R.error("失败");

        }
        if (emp.getStatus() == 0) {
            return R.error("被禁用了");

        }
        request.getSession().setAttribute("employee", emp.getId());


        return R.success(emp);
    }

    //User logout!
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {

        request.getSession().removeAttribute("employee");


        return R.success("退出成功");
    }

    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("新增员工 {}", employee.toString());
        R<String> stringR = employeeService.save1(request, employee);


        return stringR;
    }

    //分页查询
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        R<Page> pageR = employeeService.page1(page, pageSize, name);


        return pageR;
    }

    //更新
    @PutMapping
    public R<String> update(HttpServletRequest request, @RequestBody Employee employee) {
        System.out.println(employee.toString());
        long id = Thread.currentThread().getId();
        log.info("id+{}", id);
        return employeeService.update(request, employee);
    }

    //回显数据
    @GetMapping("/{id}")
    public R<Employee> getbyid(@PathVariable Long id) {
        System.out.println("回显");
        ;

        return employeeService.getid(id);
    }
}
